"""Agent管理器模块"""
import json
import logging
from agents import create_agent
from agents.deep_agent import create_deep_agent_instance
from tools import DataQueryTool, KnowledgeBaseSearchTool, PlanManagerTool, FileSystemTool, TavilySearchTool, WebBrowserTool
from model.models import AgentConfig, ModelConfig, ToolConfig
from database import SessionLocal
from config.config import DEFAULT_MODEL

logger = logging.getLogger(__name__)

# 全局 Agent 实例
_agent_instance = None
_agent_type = "langgraph"

# 工具映射表
TOOL_MAP = {
    "data_query": DataQueryTool,
    "knowledge_base": KnowledgeBaseSearchTool,
    "plan_manager": PlanManagerTool,
    "file_system": FileSystemTool,
    "tavily_search": TavilySearchTool,
    "web_browser": WebBrowserTool
}

def get_agent():
    """获取当前 Agent 实例"""
    global _agent_instance
    if _agent_instance is None:
        init_agent()
    return _agent_instance

def get_agent_type():
    """获取当前 Agent 类型"""
    global _agent_type
    return _agent_type

def init_agent(force_reload: bool = False):
    """初始化或重新加载 Agent"""
    global _agent_instance, _agent_type
    
    if _agent_instance is not None and not force_reload:
        return

    logger.info("正在初始化 Agent...")
    
    db = SessionLocal()
    try:
        # 查找激活的配置
        active_config = db.query(AgentConfig).filter(AgentConfig.is_active == True).first()
        
        tools_to_use = []
        model_name = DEFAULT_MODEL
        system_prompt = None
        api_key = None
        base_url = None
        agent_type = "langgraph"
        
        if active_config:
            logger.info(f"加载激活的 Agent 配置: {active_config.name}")
            model_name = active_config.model
            system_prompt = active_config.system_prompt
            agent_type = getattr(active_config, 'agent_type', 'langgraph')
            logger.info(f"Agent配置的模型: {model_name}, 类型: {agent_type}")
            
            # 查找对应的模型配置
            model_config = db.query(ModelConfig).filter(
                ModelConfig.model == model_name,
                ModelConfig.is_disabled == False
            ).first()
            
            if model_config:
                logger.info(f"找到模型配置: model={model_config.model}, base_url={model_config.base_url}")
                api_key = model_config.api_key
                base_url = model_config.base_url
            else:
                logger.warning(f"未找到模型 {model_name} 的配置，使用环境变量")
                all_models = db.query(ModelConfig).all()
                logger.info(f"数据库中的所有模型: {[m.model for m in all_models]}")
            
            # 解析工具
            try:
                tool_names = json.loads(active_config.tools)
                logger.info(f"Agent配置的工具: {tool_names}")
                for name in tool_names:
                    if name in TOOL_MAP:
                        # 检查工具是否启用
                        tool_config = db.query(ToolConfig).filter(ToolConfig.key == name).first()
                        if tool_config and not tool_config.is_enabled:
                            logger.info(f"工具 {name} 已禁用，跳过加载")
                            continue
                        tools_to_use.extend(TOOL_MAP[name])
                logger.info(f"加载的工具数量: {len(tools_to_use)}")
                if not tools_to_use:
                    logger.info("Agent配置未启用任何工具，将以纯对话模式运行")
            except Exception as e:
                logger.error(f"解析工具配置失败: {e}")
                tools_to_use = DataQueryTool + KnowledgeBaseSearchTool + PlanManagerTool
        else:
            logger.info("未找到激活的 Agent 配置，使用默认配置")
            tools_to_use = DataQueryTool + KnowledgeBaseSearchTool + PlanManagerTool
            
        # 创建 Agent
        logger.info(f"准备创建Agent: type={agent_type}, model={model_name}, api_key={'***' if api_key else None}, base_url={base_url}, tools={len(tools_to_use)}")
        
        if agent_type == "deepagent":
            _agent_instance = create_deep_agent_instance(
                system_prompt=system_prompt,
                model_name=model_name,
                api_key=api_key,
                base_url=base_url
            )
            _agent_type = "deepagent"
        else:
            _agent_instance = create_agent(
                tools=tools_to_use,
                model_name=model_name,
                system_prompt=system_prompt,
                api_key=api_key,
                base_url=base_url
            )
            _agent_type = "langgraph"
        
        logger.info(f"Agent 初始化完成, 类型: {_agent_type}")
        
    except Exception as e:
        logger.error(f"Agent 初始化出错: {e}")
        if _agent_instance is None:
            tools_to_use = DataQueryTool + KnowledgeBaseSearchTool + PlanManagerTool
            _agent_instance = create_agent(tools_to_use, DEFAULT_MODEL)
            _agent_type = "langgraph"
    finally:
        db.close()

def reload_agent():
    """强制重新加载 Agent"""
    init_agent(force_reload=True)
